﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Wsitech.BLL;
using Wsitech.Model;
using System.IO;
using Wsitech.Utility;

public partial class Backend_ReportAdd : BackendPageBase
{
    private readonly string sitemapid = HttpContext.Current.Request["sitemapId"] ?? "";
    private readonly string tid = HttpContext.Current.Request["tid"] ?? "";
    /// <summary>
    /// 获取栏目名称
    /// </summary>
    public string SiteMapName
    {
        get
        {
            SiteMapInfo map = null;
            if (!string.IsNullOrEmpty(sitemapid))
            {
                map = SiteMapInfoBLL.Instance.GetDetail(sitemapid);
                if (map != null)
                {
                    return map.SitemapName;
                }
            }
            else if (!string.IsNullOrEmpty(tid))
            {
                TextInfo info = TextInfoBLL.Instance.GetDetail(tid);
                map = SiteMapInfoBLL.Instance.GetDetail(info.SitemapId);
            }
            if (map != null)
            {
                return map.SitemapName;
            }
            else
            {
                return "";
            }

        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState["back"] = Request.UrlReferrer.ToString();
            bindCompany();

            if (tid != "")
            {
                initReport(tid);
            }
        }
    }

    //初始化要编辑的数据
    private void initReport(string tid)
    {
        TextInfo info = TextInfoBLL.Instance.GetDetail(tid);
        if (info != null)
        {
            ddlCompany.SelectedValue = info.CompanyId;
            txtTitle.Text = info.Title;
            txtSubTitle.Text = info.SubTitle;
            txtAuthor.Text = info.Author;
            txtMediaName.Text = info.MediaName;//媒体名称
            cbxIsTop.Checked = info.IsTop;
            txtContent.Text = info.Content;
            txtKeyWords.Text = string.Join(",", KeywordBLL.Instance.GetListByTextInfoId(tid).Select(k => k.Content));
            txtReferenceUrl.Text = info.ReferenceUrl;
            txtMediaPublishTime.Text = info.MediaPublishTime.ToString("yyyy-MM-dd");
            txtPublishTime.Text = info.PublishTime.ToString("yyyy-MM-dd");

            //资源文件 
            if (File.Exists(Server.MapPath(info.SourcePath)))
            {
                lbtnDelSource.Text = string.Format("点击删除【{0}】", Path.GetFileName(info.SourcePath));
                lbSourcePath.Text = "http://" + Request.Url.Authority + info.SourcePath;
            }
            else
            {
                lbtnDelSource.Visible = false;
            }
        }
    }

    //绑定公司信息
    private void bindCompany()
    {
        ddlCompany.DataSource = CompanyInfoBLL.Instance.GetList();
        ddlCompany.DataTextField = "CompanyName";
        ddlCompany.DataValueField = "CompanyId";
        ddlCompany.DataBind();

        ddlCompany.Items.Insert(0, new ListItem("=请选择=", "0"));
    }

    //提交信息
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (CheckParams())
        {
            //下载资源
            string sourcePath = "";
            if (FileUpload2.HasFile)
            {
                string ext = Path.GetExtension(FileUpload2.FileName).ToLower();
                if (ext == ".pdf")
                {
                    string dir = Server.MapPath(TextInfoBLL.Instance.GetSourceDir());
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    sourcePath = TextInfoBLL.Instance.GetSourceDir() + FileUpload2.FileName;
                    FileUpload2.SaveAs(Server.MapPath(sourcePath));
                }
                else
                {
                    base.Alert("资源只支持PDF文件");
                    return;
                }
            }

            //处理关键字
            string[] keys = txtKeyWords.Text.Trim().Replace('，', ',').Split(',');
            IList<String> keywords = new List<string>();
            foreach (string key in keys)
            {
                //关键字不重复且不为空
                if (key.Trim() != "" && !keywords.Contains(key))
                {
                    keywords.Add(key);
                }
            }

            if (Request["tid"] == null)
            {
                //添加
                TextInfoBLL.Instance.AddReport(
                    sitemapid,
                    ddlCompany.SelectedValue,
                    txtTitle.Text.Trim(),
                    txtSubTitle.Text.Trim(),
                    "",//中文版不需要Summary字段
                    txtMediaName.Text.Trim(),
                    txtAuthor.Text.Trim(),
                    cbxIsTop.Checked,
                    txtContent.Text,
                    keywords,
                    txtReferenceUrl.Text.Trim(),
                    sourcePath,
                    DateTime.Parse(txtMediaPublishTime.Text.Trim()),
                    DateTime.Parse(txtPublishTime.Text.Trim())
                    );
            }
            else
            {
                //编辑
                TextInfo info = TextInfoBLL.Instance.GetDetail(tid);
                if (info != null)
                {
                    info.CompanyId = ddlCompany.SelectedValue;
                    info.Title = txtTitle.Text.Trim();
                    info.SubTitle = txtSubTitle.Text.Trim();
                    info.MediaName = txtMediaName.Text.Trim();
                    info.Author = txtAuthor.Text.Trim();
                    info.IsTop = cbxIsTop.Checked;
                    info.Content = txtContent.Text;
                    info.ReferenceUrl = txtReferenceUrl.Text.Trim();
                    if (sourcePath != "")
                    {
                        info.SourcePath = sourcePath;
                    }
                    info.MediaPublishTime = DateTime.Parse(txtMediaPublishTime.Text.Trim());
                    info.PublishTime = DateTime.Parse(txtPublishTime.Text.Trim());
                    info.UpdateTime = DateTime.Now;
                    TextInfoBLL.Instance.Update(info);

                    if (keywords != null && keywords.Count > 0)
                    {
                        TextInfoKeyRelaBLL.Instance.AddRela(tid, keywords);
                    }
                }
            }



            Response.Redirect(ViewState["back"].ToString());
        }

    }

    //删除下载资源
    protected void DeleteSource(object sender, EventArgs e)
    {
        TextInfo info = TextInfoBLL.Instance.GetDetail(tid);
        if (info != null)
        {
            string filepath = Server.MapPath(info.SourcePath);
            //修改数据
            info.SourcePath = "";
            TextInfoBLL.Instance.Update(info);

            //删除文件 
            if (File.Exists(filepath))
            {
                File.Delete(filepath);
            }
        }
        Response.Redirect(ViewState["back"].ToString());
    }
    //检查参数
    private bool CheckParams()
    {
        //公司名称
        if (ddlCompany.SelectedIndex == 0)
        {
            base.Alert("请选择所属公司！");
            return false;
        }
        //标题
        if (txtTitle.Text.Trim() == "")
        {
            base.Alert("标题不能为空！");
            return false;
        }
        else
        {
            if (txtTitle.Text.Trim().Length > 150)
            {
                base.Alert("标题文字不能超过150字");
                return false;
            }
            if (TextInfoBLL.Instance.TitleExists(txtTitle.Text.Trim(), tid))
            {
                base.Alert("该标题已经存在！");
                return false;
            }
        }
        //副标题
        if (txtSubTitle.Text.Trim().Length > 50)
        {
            base.Alert("副标题不能超过50字");
            return false;
        }
        //媒体名称
        if (txtMediaName.Text.Trim() == "")
        {
            base.Alert("媒体名称不能为空！");
            return false;
        }
        else
        {
            if (txtMediaName.Text.Trim().Length > 40)
            {
                base.Alert("媒体名称不超过40字");
                return false;
            }
        }

        //作者
        if (txtAuthor.Text.Trim().Length > 30)
        {
            base.Alert("作者不能超过30字");
            return false;
        }
        //正文
        if (txtContent.Text.Trim() == "")
        {
            base.Alert("正文不能为空！");
            return false;
        }
        else
        {
            if (txtContent.Text.Trim().Length > 50000)
            {
                base.Alert("正文不能超过50000字");
                return false;
            }
        }
        //媒体发布时间
        try
        {

            DateTime.Parse(txtMediaPublishTime.Text.Trim());
        }
        catch (Exception)
        {
            Alert("媒体发布时间格式不正确！");
            return false;
        }
        //信息发布时间
        try
        {

            DateTime.Parse(txtPublishTime.Text.Trim());
        }
        catch (Exception)
        {
            Alert("信息发布时间格式不正确！");
            return false;
        }
        return true;
    }
}